
const express = require("express");
const companyService = require("../../node/service/companyService.js");
const { resSuc, resErr } = require('../utils/resMsg.js');
const bodyParser = require("body-parser");

const router = express.Router();

router.get("/", (req, res) => {
    companyService.getAll().then(rows => {
        res.json(resSuc(rows));
    }).catch(err => {
        res.json(resErr(500, err.message));
    })
});

router.post("*", bodyParser.urlencoded({ extended: false }));

// Add
router.post("/add", (req, res) => {
    companyService.add(req.body).then(lastID => {
        res.json(resSuc(lastID));
    }).catch(err => {
        res.json(resErr(400, err.message));
    })
})

// Delete
router.post("/delete", (req, res) => {
    companyService.delete(req.body.id).then(() => { 
        res.json(resSuc());
    }).catch(err => {
        res.json(resErr(400, err.message));
    })
});

// Update
router.post("/update", (req, res) => {
    companyService.update(req.body).then(() => { 
        res.json(resSuc());
    }).catch(err => {
        res.json(resErr(400, err.message));
    })
});

// save data to local file
router.post("/save", (req, res) => {
    companyService.saveAllCompanies().then(() => { 
        res.json(resSuc())
    }).catch(err => { 
        res.json(resErr(500, err.message));
    })
})

module.exports = router;
